package com.shfl.controller;

import com.alibaba.fastjson.JSON;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import model.res.ResultRes;
import service.RectD;
import stock.Stock;
import util.Check;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.List;

public class ConvertImageContorller  implements Initializable {

    /**
     * 文件选择
     */
    @FXML
    private Button selectPic ;

    /**
     * 下拉框
     */
    @FXML
    private ComboBox selectType ;

    /**
     * 图片转换
     */
    @FXML
    private Button convertImage ;

    /**
     * API Key
     */
    @FXML
    private TextField clientId ;

    /**
     * Secret Key
     */
    @FXML
    private TextField clientSecret ;

    @FXML
    private TextArea content;

    @FXML
    private TextField selectPicPath;

    @FXML
    private Button captureConversion;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        List<String> list = new ArrayList<>();
        list.add("通用文字识别");
        list.add("通用文字识别（高精度版）");
//        list.add("手写文字识别");
//        list.add("身份证识别");
//        list.add("银行卡识别");
//        list.add("识别营业执照");
//        list.add("护照识别");
//        list.add("名片识别");
//        list.add("户口识别");
//        list.add("通用票据识别");
//        list.add("增值税发票识别");

        this.selectType.setItems(FXCollections.observableArrayList(list));
        this.selectType.getSelectionModel().selectFirst();
        Stock.POST_URL =  "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
        this.selectType.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                Stock.selectTypeIndex= selectType.getItems().indexOf(newValue.toString());
                Stock.POST_URL = Stock.IDENTIFY_TYPE_MAP.get(selectType.getItems().indexOf(newValue.toString()));
        }

        });

        // 选择文件
        this.selectPic.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            // 只能够获取的文件  //PNG、JPG、JPEG、BMP
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("PNG", "*.png"),
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("JPEG", "*.jpeg"),
                    new FileChooser.ExtensionFilter("BMP", "*.bmp"));

            Window window = ((Node) event.getSource()).getScene().getWindow();
            File file = fileChooser.showOpenDialog(window);
            if (file != null) {
                this.selectPicPath.setText(file.getAbsolutePath());
            }
        });


        //团片转换按钮
        this.convertImage.setOnAction(event -> {
            try {
                String beenJson = Check.checkFile(this.selectPicPath.getText());
                Map<String, Object> resultMap = JSON.parseObject(beenJson).getInnerMap();
                if(resultMap.containsKey("error_code")){
                    this.content.setText(Stock.ErrorType.desc(Integer.parseInt(resultMap.get("error_code").toString())));
                    return;
                }
                this.content.setText(new ResultRes(Stock.selectTypeIndex,Check.checkFile(this.selectPicPath.getText())).getResult());
            } catch (URISyntaxException e) {
                this.content.setText(e.getMessage());
            } catch (IOException e) {
                this.content.setText(e.getMessage());
            }catch (Exception e){
                this.content.setText(e.getMessage());
            }
        });


        this.captureConversion.setOnAction(event -> {
            try{
                Stock.CONVERT_IMAGE_STAGE.hide();
            }catch (Exception el){
                el.printStackTrace();
            }
            Thread Thread1= new Thread(new runnAble11());
            Thread1.start();
//            try {
//                Thread.sleep(10000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            try {
                Thread1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread1.getState());

           setCaptureConversion(RectD.getInstance().getResults());
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            Stock.CONVERT_IMAGE_STAGE.show();
         //   getResults(gd);

        });

    }

    public void getResults(GraphicsDevice gd){
        if(RectD.getInstance().getResults()!=null){
            System.out.print("Stock.rd.getResults():"+RectD.getInstance().getResults());
            setCaptureConversion(RectD.getInstance().getResults());
        }else{
            if(RectD.getInstance().getResultsCount().equals(10)){
                content.setText("转义字符过多！");
                return;
            }
            RectD.getInstance().setResultsCount(RectD.getInstance().getResultsCount()+1);
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            getResults(gd);
        }
    }

    public  void setCaptureConversion(String str){
        System.out.print("788897789879");
        try {
            Map<String, Object> resultMap = JSON.parseObject( str).getInnerMap();
            if(resultMap.containsKey("error_code")){
                content.setText(Stock.ErrorType.desc(Integer.parseInt(resultMap.get("error_code").toString())));
                return;
            }
            content.setText(new ResultRes(Stock.selectTypeIndex,str).getResult());
        }catch (Exception e){
            //e.printStackTrace();
            content.setText(e.getMessage());
        }
    }
    public static void main(String[] args) {

    }
}
class runnAble11 implements Runnable{
    @Override
    public void run() {
        synchronized (Stock.obj){
            RectD rd = RectD.getInstance();
            GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment()
                    .getDefaultScreenDevice();
            gd.setFullScreenWindow(rd);
            try {
                Stock.obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            rd.getDefaultCloseOperation();

        }

    }


}
